
<template>
  <div class="asset-inventory-execute">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>执行盘点任务</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <!-- 任务信息 -->
      <el-descriptions title="任务信息" :column="3" border class="task-info">
        <el-descriptions-item label="任务编号">{{ taskInfo.taskNo }}</el-descriptions-item>
        <el-descriptions-item label="任务类型">{{ getTaskTypeLabel(taskInfo.taskType) }}</el-descriptions-item>
        <el-descriptions-item label="执行部门">{{ taskInfo.department }}</el-descriptions-item>
        <el-descriptions-item label="执行人">{{ taskInfo.executor }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">{{ taskInfo.startDate }}</el-descriptions-item>
        <el-descriptions-item label="结束日期">{{ taskInfo.endDate }}</el-descriptions-item>
        <el-descriptions-item label="任务状态">
          <el-tag :type="getStatusType(taskInfo.status)">{{ getStatusLabel(taskInfo.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="盘点进度">{{ taskInfo.progress }}%</el-descriptions-item>
        <el-descriptions-item label="任务二维码">
          <el-image :src="taskInfo.qrCode" style="width: 100px; height: 100px" />
        </el-descriptions-item>
      </el-descriptions>

      <!-- 盘点方式选择 -->
      <div class="inventory-method">
        <h3>盘点方式</h3>
        <el-radio-group v-model="inventoryMethod" @change="handleMethodChange">
          <el-radio label="manual">手工盘点</el-radio>
          <el-radio label="scan">扫码盘点</el-radio>
        </el-radio-group>
      </div>

      <!-- 手工盘点 -->
      <div v-if="inventoryMethod === 'manual'" class="manual-inventory">
        <h3>资产清单</h3>
        <el-table :data="assetList" border style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="code" label="资产编码" width="120" />
          <el-table-column prop="name" label="资产名称" width="180" />
          <el-table-column prop="category" label="资产分类" width="120">
            <template #default="scope">
              <el-tag :type="getCategoryType(scope.row.category)">
                {{ getCategoryLabel(scope.row.category) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="model" label="规格型号" width="150" />
          <el-table-column prop="location" label="存放位置" width="150" />
          <el-table-column prop="user" label="使用人" width="120" />
          <el-table-column prop="status" label="资产状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="盘点状态" width="100">
            <template #default="scope">
              <el-tag :type="getInventoryStatusType(scope.row.inventoryStatus)">
                {{ getInventoryStatusLabel(scope.row.inventoryStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button 
                v-if="scope.row.inventoryStatus !== 'completed'" 
                link type="primary" 
                @click="handleConfirmAsset(scope.row)"
              >
                确认盘点
              </el-button>
              <el-button 
                v-if="scope.row.inventoryStatus === 'completed'" 
                link type="primary" 
                @click="handleViewDetail(scope.row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="batch-operation">
          <el-button type="primary" @click="handleBatchConfirm">批量确认</el-button>
          <el-button @click="handleBatchException">批量异常</el-button>
        </div>
      </div>

      <!-- 扫码盘点 -->
      <div v-if="inventoryMethod === 'scan'" class="scan-inventory">
        <h3>扫码盘点</h3>
        <div class="scan-area">
          <el-input
            v-model="scanCode"
            placeholder="请输入资产编码或扫描二维码"
            clearable
            @keyup.enter="handleScanAsset"
          >
            <template #append>
              <el-button icon="Scan" @click="handleScanQR">扫码</el-button>
            </template>
          </el-input>
        </div>

        <div v-if="scannedAsset" class="scanned-asset">
          <h4>资产信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="资产编码">{{ scannedAsset.code }}</el-descriptions-item>
            <el-descriptions-item label="资产名称">{{ scannedAsset.name }}</el-descriptions-item>
            <el-descriptions-item label="资产分类">
              <el-tag :type="getCategoryType(scannedAsset.category)">
                {{ getCategoryLabel(scannedAsset.category) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="规格型号">{{ scannedAsset.model }}</el-descriptions-item>
            <el-descriptions-item label="存放位置">{{ scannedAsset.location }}</el-descriptions-item>
            <el-descriptions-item label="使用人">{{ scannedAsset.user }}</el-descriptions-item>
          </el-descriptions>

          <div class="scan-operation">
            <el-form :model="scanForm" label-width="100px">
              <el-form-item label="盘点状态">
                <el-radio-group v-model="scanForm.status">
                  <el-radio label="normal">正常</el-radio>
                  <el-radio label="exception">异常</el-radio>
                  <el-radio label="missing">盘亏</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注说明" v-if="scanForm.status !== 'normal'">
                <el-input
                  v-model="scanForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入异常情况说明"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleConfirmScan">确认盘点</el-button>
                <el-button @click="resetScanForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 盘点进度 -->
      <div class="inventory-progress">
        <h3>盘点进度</h3>
        <el-progress :percentage="taskInfo.progress" :color="progressColor" />
        <div class="progress-text">
          <span>已盘点：{{ taskInfo.completedCount }}</span>
          <span>未盘点：{{ taskInfo.pendingCount }}</span>
          <span>异常：{{ taskInfo.exceptionCount }}</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 任务信息
const taskInfo = reactive({
  id: 1,
  taskNo: 'PD20230001',
  taskType: 'department',
  department: '技术部',
  executor: '张三',
  startDate: '2023-12-01',
  endDate: '2023-12-15',
  status: 'executing',
  progress: 65,
  completedCount: 16,
  pendingCount: 9,
  exceptionCount: 2,
  qrCode: 'https://picsum.photos/seed/qrcode/200/200.jpg'
})

// 盘点方式
const inventoryMethod = ref('manual')

// 资产列表
const assetList = ref([
  {
    id: 1,
    code: 'ZC20230001',
    name: '笔记本电脑',
    category: 'fixed',
    model: 'ThinkPad X1 Carbon',
    location: '总部A座501',
    user: '张三',
    status: 'in_use',
    inventoryStatus: 'completed'
  },
  {
    id: 2,
    code: 'ZC20230002',
    name: '办公桌',
    category: 'low_value',
    model: '标准办公桌',
    location: '总部A座502',
    user: '李四',
    status: 'in_use',
    inventoryStatus: 'pending'
  }
])

// 扫码盘点相关
const scanCode = ref('')
const scannedAsset = ref(null)
const scanForm = reactive({
  status: 'normal',
  remark: ''
})

// 进度条颜色
const progressColor = computed(() => {
  if (taskInfo.progress < 30) return '#F56C6C'
  if (taskInfo.progress < 70) return '#E6A23C'
  return '#67C23A'
})

// 获取任务类型标签
const getTaskTypeLabel = (taskType) => {
  const typeMap = {
    department: '部门盘点',
    check: '检查盘点'
  }
  return typeMap[taskType] || taskType
}

// 获取资产分类标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    fixed: '固定资产',
    low_value: '低值易耗品',
    lease: '租赁资产',
    lease_improvement: '租入固定资产改良'
  }
  return categoryMap[category] || category
}

// 获取资产分类类型
const getCategoryType = (category) => {
  const typeMap = {
    fixed: '',
    low_value: 'success',
    lease: 'warning',
    lease_improvement: 'info'
  }
  return typeMap[category] || ''
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待执行',
    executing: '执行中',
    completed: '已完成',
    expired: '已过期',
    in_use: '在用',
    idle: '闲置',
    maintenance: '维修中',
    scrapped: '已报废'
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    executing: 'primary',
    completed: 'success',
    expired: 'danger',
    in_use: 'success',
    idle: 'info',
    maintenance: 'warning',
    scrapped: 'danger'
  }
  return typeMap[status] || ''
}

// 获取盘点状态标签
const getInventoryStatusLabel = (status) => {
  const statusMap = {
    pending: '未盘点',
    completed: '已盘点',
    exception: '异常'
  }
  return statusMap[status] || status
}

// 获取盘点状态类型
const getInventoryStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    completed: 'success',
    exception: 'danger'
  }
  return typeMap[status] || ''
}

// 盘点方式变化处理
const handleMethodChange = (value) => {
  console.log('盘点方式：', value)
}

// 返回列表
const handleBack = () => {
  router.push('/asset-inventory')
}

// 确认资产盘点
const handleConfirmAsset = (row) => {
  ElMessageBox.confirm(
    `确定要确认资产 "${row.name}" 盘点完成吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    // 更新资产盘点状态
    const index = assetList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      assetList.value[index].inventoryStatus = 'completed'
      // 更新进度
      taskInfo.completedCount++
      taskInfo.pendingCount--
      taskInfo.progress = Math.round(taskInfo.completedCount / (taskInfo.completedCount + taskInfo.pendingCount) * 100)
    }
    ElMessage.success('确认成功')
  }).catch(() => {
    ElMessage.info('已取消确认')
  })
}

// 查看资产详情
const handleViewDetail = (row) => {
  router.push(`/assets/detail/${row.id}`)
}

// 批量确认
const handleBatchConfirm = () => {
  ElMessageBox.confirm(
    '确定要批量确认选中的资产盘点完成吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.success('批量确认成功')
  }).catch(() => {
    ElMessage.info('已取消批量确认')
  })
}

// 批量异常
const handleBatchException = () => {
  ElMessageBox.confirm(
    '确定要将选中的资产标记为异常吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('批量标记异常成功')
  }).catch(() => {
    ElMessage.info('已取消批量标记')
  })
}

// 扫码
const handleScanQR = () => {
  ElMessage.info('请使用手机扫描二维码')
  // 实际应该调用扫码功能
}

// 扫码资产
const handleScanAsset = () => {
  if (!scanCode.value) {
    ElMessage.warning('请输入资产编码')
    return
  }

  // 模拟根据编码获取资产信息
  const asset = assetList.value.find(item => item.code === scanCode.value)
  if (asset) {
    scannedAsset.value = asset
  } else {
    ElMessage.error('未找到该资产信息')
  }
}

// 确认扫码盘点
const handleConfirmScan = () => {
  if (!scannedAsset.value) {
    ElMessage.warning('请先扫描资产')
    return
  }

  if (scanForm.status === 'normal') {
    // 更新资产盘点状态
    const index = assetList.value.findIndex(item => item.id === scannedAsset.value.id)
    if (index !== -1) {
      assetList.value[index].inventoryStatus = 'completed'
      // 更新进度
      taskInfo.completedCount++
      taskInfo.pendingCount--
      taskInfo.progress = Math.round(taskInfo.completedCount / (taskInfo.completedCount + taskInfo.pendingCount) * 100)
    }
    ElMessage.success('盘点成功')
  } else {
    // 标记异常
    const index = assetList.value.findIndex(item => item.id === scannedAsset.value.id)
    if (index !== -1) {
      assetList.value[index].inventoryStatus = 'exception'
      // 更新进度
      taskInfo.exceptionCount++
      taskInfo.pendingCount--
      taskInfo.progress = Math.round(taskInfo.completedCount / (taskInfo.completedCount + taskInfo.pendingCount) * 100)
    }
    ElMessage.success('已标记异常')
  }

  // 重置表单
  resetScanForm()
}

// 重置扫码表单
const resetScanForm = () => {
  scanCode.value = ''
  scannedAsset.value = null
  scanForm.status = 'normal'
  scanForm.remark = ''
}
</script>

<style scoped>
.asset-inventory-execute {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-info {
  margin-bottom: 20px;
}

.inventory-method, .manual-inventory, .scan-inventory, .inventory-progress {
  margin-bottom: 20px;
}

.scan-area {
  margin-bottom: 20px;
}

.scanned-asset {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.scan-operation {
  margin-top: 20px;
  max-width: 500px;
}

.batch-operation {
  margin-top: 20px;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}
</style>
